package ReentrantLock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2022-12-28
 * Time: 9:43
 */
public class TestDemo5 {
    private static boolean isCigarette;
    private static boolean isTakeOut;

    private static ReentrantLock ROOM = new ReentrantLock();
    //等烟的休息室
    private static Condition waitCigaretteSet = ROOM.newCondition();
    //等外卖的休息室
    private static Condition waitTakeOutSet = ROOM.newCondition();

    public static void main(String[] args) throws InterruptedException {
        //小南线程等待香烟
        new Thread(()->{
            ROOM.lock();
            try {
                System.out.println("是否有香烟" + isCigarette);
                while (!isCigarette){
                    System.out.println("没有烟,等待一会");
                    try {
                        waitCigaretteSet.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("小南开始干活");
            }finally {
                ROOM.unlock();
            }
        },"小南").start();

        //小女线程等待外卖
        new Thread(()->{
            ROOM.lock();
            try {
                System.out.println("是否有外卖" + isTakeOut);
                while(!isTakeOut){
                    System.out.println("没有外卖,等待一会");
                    try {
                        waitTakeOutSet.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }finally {
                ROOM.unlock();
            }
            System.out.println("小女吃完外卖,开始干活");
        },"小女").start();

        Thread.sleep(1000);

        new Thread(()->{
           ROOM.lock();
           try {
               isCigarette = true;
               waitCigaretteSet.signal();
           }finally {
               ROOM.unlock();
           }
        },"送烟的").start();

        new Thread(()->{
            ROOM.lock();
            try {
                isTakeOut = true;
                waitTakeOutSet.signal();
            }finally {
                ROOM.unlock();
            }
        },"外卖小哥").start();
    }
}